const express = require('express');

const routes = express.Router();

const md5 = require('md5-node');

//引入mysql
const mysql = require('mysql');
//创建连接池
var pool = mysql.createPool({
    connectionLimit : 10,
    host : 'localhost',
    user : 'root',
    password : 'root',
    database : 'stumsg'
})

routes.get('/',(req,resp)=>{
    resp.render('chenck')
})

    .post('/',(req,resp)=>{
        // console.log(req.body)
    //    将原密码  新密码 存储进cookie
        var old = md5( req.body.old.trim() );
        //拿原来的密码对比这个输入框的原密码 不相同终止程序  获取cookie
        var oldpwd = req.cookies.pwd;
        if(old != oldpwd){
            resp.redirect('/chenck')
        }
        //新密码  和 确定密码对比  不相同终止程序
        var news = req.body.news.trim();
        var chenck = req.body.chenck.trim();
        if(news != chenck){
            resp.redirect('/chenck')
        }
        var uid = req.cookies.uid;
    //    执行sql语句
        var sql = `UPDATE stu_list SET pwd=MD5('${news}') WHERE uid = ${uid}`;
        // console.log(sql)
        pool.getConnection(function(err,connection){
            if(err) throw err;
            //    链接成功
            connection.query(sql,(error,result)=> {

                //    释放连接   关闭数据库
                connection.release();

                if(result){
                    //修改成功  重定向回登录页
                    resp.redirect('/')
                }

                //sql语句出错执行报错处理
                if(error) throw error;
            })
        })
    })

//暴露接口
module.exports = routes;